/**
 * 商品分类页面
 */
import React,{useState, useEffect} from 'react';
import axios from 'axios';
import { Form, Button, Modal, Input, Dropdown, message } from 'antd';
import html2canvas from 'html2canvas';
import { Document, Packer, Paragraph, TextRun, Table as WordTable, TableRow, TableCell } from 'docx';

interface Type{
  name:string
}

interface Values{
  name:string
}

const ProductCategory: React.FC = () => {
  const [form] = Form.useForm();
  const [open,setOpen] = useState(false)
  const [typeList,setTypeList] = useState<Type[]>([])
  const [formValues] = useState<Values>({
    name:'',
  })
  const [exportLoading, setExportLoading] = useState(false);
  useEffect(()=>{
    getTypeList()
  },[])
  
  const getTypeList = async () =>{
    const res =  await axios.post('http://localhost:3000/hsl/type/list')
    console.log(res.data.data)
    setTypeList(res.data.data)
  }
  const handelSubmit = async()=>{
    const values = await form.validateFields()
    console.log(values)
    await axios.post('http://localhost:3000/hsl/type/add',values)
    getTypeList()
    setOpen(false)
  }
  
  // 导出为Excel (CSV格式)
  const exportToExcel = () => {
    setExportLoading(true);
    try {
      // 准备CSV数据
      const headers = ['分类序号', '分类名称'];
      const rows = [headers];
      
      // 添加数据行
      typeList.forEach((item, index) => {
        rows.push([
          (index + 1).toString(),
          item.name
        ]);
      });
      
      // 生成CSV内容
      const csvContent = rows.map(row => 
        row.map(cell => `"${cell}"`).join(',')
      ).join('\n');
      
      // 创建下载链接
      const blob = new Blob(['\ufeff' + csvContent], { type: 'text/csv;charset=utf-8;' });
      const link = document.createElement('a');
      link.href = URL.createObjectURL(blob);
      link.download = `商品分类列表_${new Date().toISOString().split('T')[0]}.xlsx`;
      link.click();
      
      message.success('Excel导出成功');
    } catch (error) {
      console.error('导出Excel失败:', error);
      message.error('导出Excel失败');
    } finally {
      setExportLoading(false);
    }
  };

  // 导出为图片
  const exportToImage = async () => {
    setExportLoading(true);
    try {
      // 创建一个临时的容器来渲染表格数据
      const tableContainer = document.createElement('div');
      tableContainer.style.width = '800px';
      tableContainer.style.padding = '20px';
      tableContainer.style.backgroundColor = 'white';
      tableContainer.style.position = 'absolute';
      tableContainer.style.left = '-9999px';
      tableContainer.style.top = '-9999px';
      document.body.appendChild(tableContainer);

      // 添加标题
      const title = document.createElement('h2');
      title.textContent = '商品分类列表';
      title.style.textAlign = 'center';
      title.style.marginBottom = '20px';
      tableContainer.appendChild(title);

      // 添加生成时间
      const timeInfo = document.createElement('p');
      timeInfo.textContent = `生成时间: ${new Date().toLocaleString('zh-CN')}`;
      timeInfo.style.textAlign = 'center';
      timeInfo.style.marginBottom = '20px';
      tableContainer.appendChild(timeInfo);

      // 创建表格
      const table = document.createElement('table');
      table.style.width = '100%';
      table.style.borderCollapse = 'collapse';
      
      // 创建表头
      const thead = document.createElement('thead');
      const headerRow = document.createElement('tr');
      const headers = ['分类序号', '分类名称'];
      headers.forEach(headerText => {
        const th = document.createElement('th');
        th.textContent = headerText;
        th.style.border = '1px solid #ddd';
        th.style.padding = '10px';
        th.style.backgroundColor = '#f5f5f5';
        th.style.fontWeight = 'bold';
        headerRow.appendChild(th);
      });
      thead.appendChild(headerRow);
      table.appendChild(thead);

      // 创建表格内容
      const tbody = document.createElement('tbody');
      typeList.forEach((item, index) => {
        const row = document.createElement('tr');
        const data = [
          (index + 1).toString(),
          item.name
        ];
        data.forEach(cellText => {
          const td = document.createElement('td');
          td.textContent = cellText;
          td.style.border = '1px solid #ddd';
          td.style.padding = '10px';
          row.appendChild(td);
        });
        tbody.appendChild(row);
      });
      table.appendChild(tbody);
      tableContainer.appendChild(table);

      // 使用html2canvas截图
      const canvas = await html2canvas(tableContainer, {
        scale: 2, // 提高清晰度
        useCORS: true,
        backgroundColor: 'white'
      });

      // 转换为图片并下载
      const link = document.createElement('a');
      link.href = canvas.toDataURL('image/png');
      link.download = `商品分类列表_${new Date().toISOString().split('T')[0]}.png`;
      link.click();

      // 清理临时元素
      document.body.removeChild(tableContainer);
      message.success('图片导出成功');
    } catch (error) {
      console.error('导出图片失败:', error);
      message.error('导出图片失败');
    } finally {
      setExportLoading(false);
    }
  };

  // 导出为Word
  const exportToWord = async () => {
    setExportLoading(true);
    try {
      // 创建Word文档
      const doc = new Document({
        sections: [
          {
            properties: {},
            children: [
              // 添加标题
              new Paragraph({
                children: [
                  new TextRun({
                    text: '商品分类列表',
                    bold: true,
                    size: 36,
                  }),
                ],
                alignment: 'center',
                spacing: {
                  after: 240,
                },
              }),
              // 添加生成时间
              new Paragraph({
                children: [
                  new TextRun({
                    text: `生成时间: ${new Date().toLocaleString('zh-CN')}`,
                    size: 20,
                  }),
                ],
                alignment: 'center',
                spacing: {
                  after: 240,
                },
              }),
              // 创建表格
              new WordTable({
                rows: [
                  // 表头行
                  new TableRow({
                    children: [
                      new TableCell({
                        children: [new Paragraph('分类序号')],
                        shading: { fill: '#f5f5f5' },
                        borders: {
                          top: { style: 'single', size: 2, color: '000000' },
                          bottom: { style: 'single', size: 2, color: '000000' },
                          left: { style: 'single', size: 2, color: '000000' },
                          right: { style: 'single', size: 2, color: '000000' },
                        },
                      }),
                      new TableCell({
                        children: [new Paragraph('分类名称')],
                        shading: { fill: '#f5f5f5' },
                        borders: {
                          top: { style: 'single', size: 2, color: '000000' },
                          bottom: { style: 'single', size: 2, color: '000000' },
                          left: { style: 'single', size: 2, color: '000000' },
                          right: { style: 'single', size: 2, color: '000000' },
                        },
                      }),
                    ],
                  }),
                  // 数据行
                  ...typeList.map((item, index) =>
                    new TableRow({
                      children: [
                        new TableCell({
                          children: [new Paragraph((index + 1).toString())],
                          borders: {
                            top: { style: 'single', size: 2, color: '000000' },
                            bottom: { style: 'single', size: 2, color: '000000' },
                            left: { style: 'single', size: 2, color: '000000' },
                            right: { style: 'single', size: 2, color: '000000' },
                          },
                        }),
                        new TableCell({
                          children: [new Paragraph(item.name)],
                          borders: {
                            top: { style: 'single', size: 2, color: '000000' },
                            bottom: { style: 'single', size: 2, color: '000000' },
                            left: { style: 'single', size: 2, color: '000000' },
                            right: { style: 'single', size: 2, color: '000000' },
                          },
                        }),
                      ],
                    })
                  ),
                ],
              }),
            ],
          },
        ],
      });

      // 生成Word文件并下载
      const blob = await Packer.toBlob(doc);
      const link = document.createElement('a');
      link.href = URL.createObjectURL(blob);
      link.download = `商品分类列表_${new Date().toISOString().split('T')[0]}.docx`;
      link.click();

      message.success('Word导出成功');
    } catch (error) {
      console.error('导出Word失败:', error);
      message.error('导出Word失败');
    } finally {
      setExportLoading(false);
    }
  };
  return (
    <div className="min-h-screen space-y-6 p-6 bg-gray-50 dark:bg-slate-950 transition-colors">
      <div className="mb-6">
        <h2 className="text-2xl font-bold text-gray-800 dark:text-slate-100">商品分类</h2>
        <p className="text-gray-500 dark:text-slate-400 mt-1">管理商品分类信息</p>
      </div>
      
      <div className="bg-white dark:bg-slate-900/80 border border-transparent dark:border-slate-800 rounded-lg shadow p-6 transition-colors">
        {/* <p className="text-gray-600">商品分类功能开发中...</p> */}
        <div className="flex mb-4">
          <Button onClick={()=>setOpen(true)}>添加分类</Button>
          
          <Dropdown
            menu={{
              items: [
                {
                  key: 'excel',
                  label: '导出Excel',
                  onClick: exportToExcel
                },
                {
                  key: 'image',
                  label: '导出图片',
                  onClick: exportToImage
                },
                {
                  key: 'word',
                  label: '导出Word',
                  onClick: exportToWord
                }
              ]
            }}
          >
            <Button
              type="default"
              disabled={exportLoading || typeList.length === 0}
              className="ml-4"
            >
              {exportLoading ? '导出中...' : '导出数据'}
            </Button>
          </Dropdown>
        </div>
        <div className="grid grid-cols-2 gap-4">
          {typeList.map((item,index)=>{
            return (
              <div key={index} className="bg-gray-100 dark:bg-slate-900/60 border border-transparent dark:border-slate-700 p-4 rounded-md transition-colors">
                <p className="text-gray-800 dark:text-slate-100 font-bold">{item.name}</p>
              </div>
            )
          })}
        </div>
        <Modal
        title="编辑商品信息"
        open={open}
        onOk={()=>handelSubmit()}
        onCancel={()=>setOpen(false)}
      >
        <Form form={form} initialValues={formValues} layout="vertical">
          <Form.Item name="name" label="分类名称">
            <Input />
          </Form.Item>
        </Form>
      </Modal>
      </div>
    </div>
  )
}

export default ProductCategory

